package com.manage.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;


public class JsonUtils {
    private static final ObjectMapper mapper = new ObjectMapper();
    /**
     * 将java对象(数组、集合、map)转换成json字符串
     * @param t
     * @param <T>
     * @return
     */
    public static <T> String  objectToString(T t){ //对象、集合
        try {
            if(t == null)
                throw new IllegalArgumentException("对象不能为null");

            return mapper.writeValueAsString(t);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new IllegalArgumentException("属性名与json key不一致");
        }
    }
    /**
     * 将json字符串转换成java对象
     * @param json
     * @param c
     * @param <T>
     * @return
     */
    public static <T> T jsonToObject(String json,Class<T> c){
        try {
            if(json == null || json.equals(""))
                throw new IllegalArgumentException("json字符串不能为空");

            return mapper.readValue(json, c);
        } catch (IOException e) {
            e.printStackTrace();
            throw new IllegalArgumentException("属性名与json key不一致");
        }
    }

    /**
     * 将json数组格式的字符串转换成java对象集合
     * @param json
     * @param c
     * @param <T>
     * @return
     */
    public static <T> List<T> jsonToList(String json,Class<T> c){
        try {
            if(json == null || json.equals(""))
                throw new IllegalArgumentException("json字符串不能为空");

            return mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, c));
        } catch (IOException e) {
            e.printStackTrace();
            throw new IllegalArgumentException("属性名与json key不一致");
        }
    }
}